package com.syf.core.service.context;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.syf.core.service.enums.ResponseFormat;
import com.syf.core.service.enums.ResponseFormatEnums;
import lombok.Data;
import org.slf4j.helpers.MessageFormatter;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;

@Data
public class ServiceResponse<R> {
    /**
     * 响应码，000000代表成功
     */
    @NotNull
    private String respCode;

    /**
     * 响应信息
     */
    @NotNull
    private String respMsg;

    /**
     * 响应数据体对象
     */
    @Valid
    private R dataObj;

    public ServiceResponse() {
        setSuccess();
    }

    public ServiceResponse(String respCode, String respMsg) {
        this.respCode = respCode;
        this.respMsg = respMsg;
    }

    public ServiceResponse(ResponseFormat respFormat, Object... obs) {
        this.respCode = respFormat.getRespCode();
        this.respMsg = MessageFormatter.arrayFormat(respFormat.getRespMsgFmt(), obs.clone()).getMessage();
    }

    @JsonIgnore
    public void setSuccess() {
        setResp(ResponseFormatEnums.SUCCESS);
    }

    @JsonIgnore
    public void setError(String respCode, String respMsg) {
        this.respCode = respCode;
        this.respMsg = respMsg;
    }

    @JsonIgnore
    public void setError(ResponseFormat respFormat, Object... obs) {
        setResp(respFormat, obs);
    }

    @JsonIgnore
    public void setResp(ResponseFormat respFormat, Object... obs) {
        this.respCode = respFormat.getRespCode();
        this.respMsg = MessageFormatter.arrayFormat(respFormat.getRespMsgFmt(), obs.clone()).getMessage();
    }

    @JsonIgnore
    public boolean isSuccess() {
        return ResponseFormatEnums.SUCCESS.getRespCode().equals(respCode);
    }
}
